var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { CONTENT_TYPE, ERROR, HEADER, METHOD, RESPONSE_TYPE } from "./config";
import { downloadFile, request, uploadFile } from "@tarojs/taro";
class RequestData {
    executeRequest(url, requestBody) {
        this.requestParams.url = url;
        if (requestBody)
            this.requestParams.requestBody = requestBody;
        return requestData(this.requestParams);
    }
    constructor() {
        this.requestParams = {
            method: METHOD.Get,
            url: "",
            requestBody: undefined,
            headers: [],
            async: true,
            responseType: RESPONSE_TYPE.Json,
        };
    }
    get(url, requestBody) {
        return __awaiter(this, void 0, void 0, function* () {
            this.requestParams.method = METHOD.Get;
            return this.executeRequest(url, requestBody);
        });
    }
    post(url, requestBody) {
        return __awaiter(this, void 0, void 0, function* () {
            this.requestParams.method = METHOD.Post;
            return this.executeRequest(url, requestBody);
        });
    }
    delete(url, requestBody) {
        return __awaiter(this, void 0, void 0, function* () {
            this.requestParams.method = METHOD.Delete;
            return this.executeRequest(url, requestBody);
        });
    }
    put(url, requestBody) {
        return __awaiter(this, void 0, void 0, function* () {
            this.requestParams.method = METHOD.Put;
            return this.executeRequest(url, requestBody);
        });
    }
    uploadFile(url, filePath, name, formData) {
        return __awaiter(this, void 0, void 0, function* () {
            this.requestParams.url = url;
            return request_uploadFile(this.requestParams, filePath, name, formData);
        });
    }
    downloadFile(url) {
        return __awaiter(this, void 0, void 0, function* () {
            this.requestParams.url = url;
            return request_downloadFile(this.requestParams);
        });
    }
    abortRequest() {
        if (this.requestInstance)
            this.requestInstance.abort();
        else
            console.error('abortRequest()', '未获取到请求实例');
    }
    handleAbort(callback) {
        callback();
    }
    setHeader(name, value) {
        const index = this.requestParams.headers.findIndex(m => m.name === name);
        if (index >= 0)
            this.requestParams.headers[index].value = value;
        else
            this.requestParams.headers.push({ name, value });
    }
    setHeaderBearer(value) {
        const name = HEADER.Authorization;
        const data = `Bearer ${value}`;
        const index = this.requestParams.headers.findIndex(m => m.name === name);
        if (index >= 0)
            this.requestParams.headers[index].value = data;
        else
            this.requestParams.headers.push({ name, value: data });
    }
    setHeaderBasic(value) {
        const name = HEADER.Authorization;
        const data = `Basic ${value}`;
        const index = this.requestParams.headers.findIndex(m => m.name === name);
        if (index >= 0)
            this.requestParams.headers[index].value = data;
        else
            this.requestParams.headers.push({ name, value: data });
    }
    setAsync(value) {
        this.requestParams.async = value;
    }
    setTimeout(time) {
        this.requestParams.timeout = time;
    }
    setResponseType(responseType) {
        this.requestParams.responseType = responseType;
    }
    setRequest(request) {
        this.requestParams.request = request;
    }
}
RequestData.Header = HEADER;
RequestData.ContentType = CONTENT_TYPE;
RequestData.ResponseType = RESPONSE_TYPE;
RequestData.Method = METHOD;
RequestData.Error = ERROR;
/**
 * 请求封装
 * @param params          请求参数
 */
const requestData = function (params) {
    return new Promise((resolve, reject) => {
        var _a;
        try {
            // 使用 reduce 构建 header
            const header = ((_a = params.headers) === null || _a === void 0 ? void 0 : _a.reduce((acc, item) => {
                acc[item.name] = item.value;
                return acc;
            }, {})) || {};
            request({
                url: params.url,
                method: params.method,
                header,
                data: params.requestBody,
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data);
                    }
                    else {
                        reject(res);
                    }
                },
                fail: (err) => {
                    console.error('Request failed:', err);
                    reject(new Error(`Request failed: ${err.errMsg}`));
                }
            });
        }
        catch (error) {
            console.error('Request initialization failed:', error);
            reject(new Error(`Request initialization failed: ${error instanceof Error ? error.message : 'Unknown error'}`));
        }
    });
};
const request_uploadFile = function (params, filePath, name, formData) {
    return new Promise((resolve, reject) => {
        try {
            // 使用 reduce 构建 header
            const header = params.headers.reduce((acc, item) => {
                acc[item.name] = item.value;
                return acc;
            }, {});
            uploadFile({
                url: params.url,
                header,
                filePath,
                name: name !== null && name !== void 0 ? name : 'file',
                formData,
                success: (files) => {
                    if (files.statusCode === 200 || files.statusCode === 204) {
                        resolve(files.data);
                    }
                    else {
                        reject(new Error(`Upload failed with status code ${files.statusCode}`));
                    }
                },
                fail: (err) => {
                    reject(new Error(`Upload failed: ${err.errMsg}`));
                }
            });
        }
        catch (error) {
            reject(new Error(`Upload initialization failed: ${error instanceof Error ? error.message : 'Unknown error'}`));
        }
    });
};
const request_downloadFile = function (params) {
    return new Promise((resolve, reject) => {
        downloadFile({
            url: params.url,
            success: (files) => {
                if (files.statusCode === 200)
                    resolve(files.tempFilePath);
                else
                    reject(files);
            }
        });
    });
};
export default RequestData;
